﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace vueweb.Controllers
{
	[Route("home")]
	public class HomeController : BaseController
	{
		[Route("app")]
		[DirectAccessAction]
		public IActionResult App()
		{
			ViewBag.isOtherLogin = false;
			ViewBag.redirect = "/";
			Dictionary<string, string> dic = new Dictionary<string, string>();
			if (!string.IsNullOrEmpty(Request.Query["redirect"]))
			{
				string redirect = Request.Query["redirect"].ToString().Trim();
				if (redirect.ToLower().StartsWith("http"))
				{
					ViewBag.redirect = redirect;
					ViewBag.isOtherLogin = true;
				}
			}
			if (Request.Query.Count > 0)
			{
				foreach (var key in Request.Query.Keys)
				{
					if (key.ToLower() != "redirect")
					{
						dic[key] = Request.Query[key];
					}
				}
			}
			ViewBag.otherQuery = JsonConvert.SerializeObject(dic);
			return View();
		}

		[Route("/Error")]
		[DirectAccessAction]
		public IActionResult Error()
		{
			IExceptionHandlerPathFeature iExceptionHandlerFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

			if (iExceptionHandlerFeature != null)
			{
				string path = iExceptionHandlerFeature.Path;
				Exception exception = iExceptionHandlerFeature.Error;
				//错误日志处理
				if (!IsAjax)
				{
					return View("Error", iExceptionHandlerFeature);
				}
				else
				{
					Response.StatusCode = 200; 
					JObject obj = new JObject();
					obj.Add("code", 50000);
					obj.Add("path", path);
					obj.Add("msg", exception.Message);
					obj.Add("trace", exception.StackTrace);					
					if (exception.InnerException != null)
					{
						obj["msg"] = exception.InnerException.Message;
						obj["trace"] = exception.InnerException.StackTrace;
					}
					return Content(obj.ToString(), JsonContentType);
				}
			}
			return View();
		}

		[Route("/Error/NotFound/{statusCode}")]
		[DirectAccessAction]
		public IActionResult NotFound(int statusCode)
		{
			var iStatusCodeReExecuteFeature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
			if (!IsAjax)
			{
				return View("NotFound", iStatusCodeReExecuteFeature.OriginalPath);
			}
			else
			{
				Response.StatusCode = 200; 
				JObject obj = new JObject();
				obj.Add("code", 40000);
				obj.Add("path", iStatusCodeReExecuteFeature.OriginalPath);				
				return Content(obj.ToString(), JsonContentType);
			}			
		}
	}
}